package leo.peersim.abcast;

import java.util.Random;

import leo.peersim.common.FSMOperationRequest;
import leo.peersim.common.MessageTrigger;

import org.apache.log4j.Logger;

import peersim.config.Configuration;
import peersim.core.CommonState;
import peersim.core.Control;
import peersim.core.Network;
import peersim.core.Node;
import peersim.edsim.EDSimulator;

/**
 * 
 * @author leo
 * @version June 19, 2009
 */
public class LoadTester implements Control {
	
	private static Logger logger = Logger.getLogger(MessageTrigger.class.getName());
	
	private final int protocolID;
	
	private int sequenceNumber = 0;
	private int _load;
	
	public LoadTester(String prefix) {
		this.protocolID = Configuration.getPid(prefix + "." + "protocol");
		this._load = Configuration.getInt(prefix + "." + "load");
	}

	/**
	 * 
	 * 
	 */
	@Override
	public boolean execute() {
		
		this.pushTraffic(this._load);
		
		return false;
	}
	
	public void pushTraffic(int load) {
		
		Random r = new Random();
		
		for(int i=0; i<load; i++) {
			
			String command = "C" + (this.sequenceNumber++);
			
			int randomInt = CommonState.r.nextInt( Network.size() );
			Node randomLeader = Network.get(randomInt);
			
			int delay = r.nextInt(1000);
			logger.debug(CommonState.getTime() + "\ttriggering request _" + command + "_ to agent[" + randomLeader.getID() + "] @ time " + delay + "...");
			FSMOperationRequest request = new FSMOperationRequest("pippo", command, delay);
			
			EDSimulator.add(delay, request, randomLeader, this.protocolID);	
		}	
	}
}